import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';
import { Response } from 'express';

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  private readonly logger = new Logger('HttpExceptionFilter');

  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest();

    // 详细记录错误信息
    this.logger.error('Exception occurred:', {
      path: request.url,
      method: request.method,
      headers: request.headers,
      query: request.query,
      body: request.body,
      exception: exception instanceof Error ? {
        name: exception.name,
        message: exception.message,
        stack: exception.stack,
      } : exception,
    });

    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    // 获取更详细的错误信息
    let message = '服务器内部错误';
    let details = null;
    
    if (exception instanceof HttpException) {
      const response = exception.getResponse();
      message = exception.message;
      
      if (typeof response === 'object') {
        details = response;
        if ('message' in response) {
          message = Array.isArray(response.message) 
            ? response.message.join(', ') 
            : String(response.message);
        }
      }
    } else if (exception instanceof Error) {
      message = exception.message;
    }

    // 添加更多调试信息
    console.error('HTTP异常详情:', {
      status,
      message,
      details,
      path: request.url,
      user: request.user,
      exception: exception instanceof Error ? {
        name: exception.name,
        message: exception.message,
        stack: exception.stack,
      } : exception,
    });

    response.status(status).json({
      code: status,
      message,
      details: process.env.NODE_ENV === 'production' ? undefined : details,
      timestamp: new Date().toISOString(),
      path: request.url,
    });
  }
}
